import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { User } from '../user';

@Component({
  selector: 'app-dynamic-form',
  templateUrl: './dynamic-form.component.html',
  styleUrls: ['./dynamic-form.component.css']
})
export class DynamicFormComponent implements OnInit {

  users: User[];
  form: FormGroup;
  payLoad: string;
  constructor() { }

  ngOnInit() {
    this.users = [
      { id: 1, name: 'Nice', record: true },
      { id: 2, name: 'Narco', record: false },
      { id: 3, name: 'Bombasto', record: true },
      { id: 4, name: 'Celeritas', record: false },
      { id: 5, name: 'Magneta', record: true }
    ];
    const group: any = {};
    this.users.forEach((user, index) => {
      if (index % 2 === 0) {
        group[user.name] = new FormControl('', {validators: [Validators.required, Validators.minLength(4)], updateOn: 'blur'});
      } else {
        group[user.name] = new FormControl(user.name || '');
      }
    });
    this.form = new FormGroup(group);
  }
  onSubmit() {
    this.payLoad = JSON.stringify(this.form.value);
  }
}
